using Digitalmes.Domain.Entities.Mes.Processes;

namespace Digitalmes.Application.Mes.Processes.Routings.Commands;

/// <summary>
/// 工艺路线创建命令。
/// </summary>
public sealed record CreateRoutingCommand(ProcRoutingDto Routing) : IRequest<IResult<bool>>;

internal sealed class CreateRoutingCommandHandler(IRepository<ProcRouting> repo) : IRequestHandler<CreateRoutingCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateRoutingCommand request, CancellationToken cancellationToken)
    {
        if (await repo.IsAnyAsync(m => m.RoutingCode == request.Routing.RoutingCode, cancellationToken))
        {
            return Result.Failure("工序路线编号已存在");
        }

        // 检查产品在此工艺路线是否唯一
        // 目前设定：同一产品在同一生产线中必须唯一（启用状态）
        if (await repo.IsAnyAsync(m => m.LineId == request.Routing.LineId
            && m.ProductId == request.Routing.ProductId
            && m.Status == EnabledStatusEnum.Enabled, cancellationToken))
        {
            return Result.Failure("该产品在此生产线中已存在可用的工艺路线");
        }

        var routing = request.Routing.Adapt<ProcRouting>();
        var ok = await repo.InsertAsync(routing, cancellationToken);
        return Result.From(ok);
    }
}
